# -*- coding: utf-8 -*-
#
# @Author  : Yang
# @Email  : yangjiaxian@ibbd.net
# @Time    : 2023/3/6
import os
from fastapi import APIRouter, Query, Depends, File, UploadFile, Body
from fastapi.responses import FileResponse
from settings import settings
from src.error import InternalException, status
from src.services.customer import CustomerServices
from src.services.file import FileServices
from src.services.log import LogServices
from src.utils import output_json, check_operator

file_app = APIRouter()


@file_app.post(path="/files", summary="上传客户的附件数据", tags=["NEW!"])
async def upload_customer_files_api(
        operator_id: int = Depends(check_operator),
        customerId: int = Body(..., title="客户ID", description="客户ID"),
        file: UploadFile = File(..., title="客户附件数据", description="客户附件数据")
):
    # 检查客户ID是否存在
    if not CustomerServices().fetch_one(customerId):
        raise InternalException(status.HTTP_601_ID_NOT_EXIST, message="客户ID不存在")

    if not os.path.exists(os.path.join(settings.FILES_DIR, str(customerId))):
        os.mkdir(os.path.join(settings.FILES_DIR, str(customerId)))
    with open(os.path.join(settings.FILES_DIR, str(customerId), file.filename), "wb") as f:
        file_content = await file.read()
        f.write(file_content)

    file_id = FileServices().create(
        customerId, file.filename,
        os.path.join(settings.FILES_DIR, str(customerId), file.filename))

    LogServices().create(operator_id, f"为ID为{customerId}的客户新增《{file.filename}》附件")
    return output_json(data={
        "id": file_id,
        "url": f"http://127.0.0.1:8000/api/v1/files/{file_id}"
    }, message="上传客户附件数据成功")


@file_app.get(path="/files", summary="获取客户的附件数据", tags=["NEW!"])
async def get_customer_files_api(
        operator_id: int = Depends(check_operator),
        customer_id: int = Query(..., title="客户ID", description="客户ID")
):
    data = FileServices().fetch_data(customer_id)
    for row in data:
        row["url"] = f"http://127.0.0.1:8000/api/v1/files/{row['id']}"
    return output_json(data=data, message="获取客户附件数据成功")


@file_app.get(path="/files/{file_id}", summary="获取附件文件", tags=["NEW!"])
async def get_customer_file_api(
        file_id: int = Query(..., title="附件ID", description="附件ID"),
):
    data = FileServices().fetch_one(file_id)
    if not data:
        raise InternalException(status.HTTP_601_ID_NOT_EXIST, message="文件不存在")

    return FileResponse(data["filepath"], filename=data["filename"])


@file_app.delete(path="/files/{file_id}", summary="删除附件文件", tags=["NEW!"])
async def get_customer_file_api(
        operator_id: int = Depends(check_operator),
        file_id: int = Query(..., title="附件ID", description="附件ID"),
):
    data = FileServices().fetch_one(file_id)
    if not data:
        raise InternalException(status.HTTP_601_ID_NOT_EXIST, message="文件不存在")

    FileServices().delete(file_id)
    return output_json(data=None, message="删除客户附件成功")
